package gui;

import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import mpo.Database;
import mpo.ExceptionNullObject;
import mpo.Klient;
import mpo.Zlecenie;

public class PDyrektora3 extends javax.swing.JPanel {

    private Ramka ramka;
    private Database db;
    DefaultListModel<String> modelDanychListy1;
    private List<Zlecenie> zlecenieList_local;
    private List<Klient> klienciList;
    private Zlecenie zlecenieDoRozliczenia;

    public PDyrektora3(Ramka r) {
        initComponents();
        this.ramka = r;
        this.db = mysql.Db_Mysql.instance();
        zlecenieList_local = db.getZlecenieList();
        klienciList = db.getKlientList();
        fillZlecenie();

    }

    public void synchonizeAllListWithDatabase() {
        System.out.println("Panel rozliczania zlecen synchronizuje sie");
        db = mysql.Db_Mysql.instance();
        zlecenieList_local = db.getZlecenieList();
        klienciList = db.getKlientList();
    }

    public void fillZlecenie() {
        modelDanychListy1 = new DefaultListModel<>();
        for (Zlecenie zlecenie : zlecenieList_local) {
            if (zlecenie.getId() == 0) {
                continue;
            }
            modelDanychListy1.addElement(zlecenie.getId() + "." + zlecenie.getNazwaZlecenia());
        }
        jList1.setModel(modelDanychListy1);
        jList1.repaint();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();

        jLabel1.setText("PANEL Dyrektora - Rozlicz Zlecenie");

        jLabel2.setText("Podsumowanie");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Do zapłaty");

        jTextField1.setEditable(false);
        jTextField1.setBackground(new java.awt.Color(255, 255, 255));
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField1KeyTyped(evt);
            }
        });

        jLabel4.setText("Kontrahent");

        jLabel5.setText("Nazwa");

        jLabel6.setText("Adres");

        jTextField4.setEditable(false);
        jTextField4.setBackground(new java.awt.Color(255, 255, 255));

        jTextField5.setEditable(false);
        jTextField5.setBackground(new java.awt.Color(255, 255, 255));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Pobrano");

        jTextField2.setEditable(false);
        jTextField2.setBackground(new java.awt.Color(255, 255, 255));
        jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField2KeyTyped(evt);
            }
        });

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Data płatności");

        jTextField3.setEditable(false);
        jTextField3.setBackground(new java.awt.Color(255, 255, 255));
        jTextField3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTextField3KeyTyped(evt);
            }
        });

        jButton1.setText("Zrealizuj zlecenie");
        jButton1.setEnabled(false);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Wyślij przypomnienie");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Menu główne");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(48, 48, 48)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(43, 43, 43)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 187, Short.MAX_VALUE)
                                    .addComponent(jTextField4)))
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(20, 20, 20))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGap(389, 389, 389)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(19, 19, 19)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(40, 40, 40)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(28, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ramka.setActivePanel(0);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
        if (jList1.getSelectedValue() == null) {
            jButton1.setEnabled(false);
            jButton2.setEnabled(false);
            return;
        }
        jButton1.setEnabled(true);
        jButton2.setEnabled(true);
        String wybor = jList1.getSelectedValue().toString();
        int idKlientaWybranegoZlecenia = 0;

        for (Zlecenie zlecenie : zlecenieList_local) {
            String s = zlecenie.getId() + "." + zlecenie.getNazwaZlecenia();
            if (s.equals(wybor)) {
                jTextField1.setText(String.valueOf(zlecenie.getDoZaplaty()));
                jTextField2.setText(String.valueOf(zlecenie.getPobrano()));
                jTextField3.setText(String.valueOf(zlecenie.getDataPlatnosciViaString()));
                idKlientaWybranegoZlecenia = zlecenie.getIdKlient();
                zlecenieDoRozliczenia = zlecenie;
                break;
            }
        }

        for (Klient klient : klienciList) {
            if (klient.getId() == idKlientaWybranegoZlecenia) {
                if (klient.getNazwa().length() > 1) {
                    jTextField4.setText(klient.getNazwa());
                } else {
                    jTextField4.setText(klient.getImie() + " " + klient.getNazwisko());
                }
                jTextField5.setText(klient.getMiasto());
                break;
            }
        }
    }//GEN-LAST:event_jList1MouseClicked

    private boolean checkIfOperatorIsSure() {
        Object[] options = {"Tak", "Nie"};
        int n = JOptionPane.showOptionDialog(null,
                "Rozliczyć zlecenie?",
                "Potwierdź",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null, options,
                options[0]);

        if (n == 1) {
            return false;
        }
        if (n == 0) {
            return true;
        }
        return false;
    }

    private void rozliczZlecenie() throws Exception {
        this.db = mysql.Db_Mysql.instance();
        int res = -5;
        res = db.rozliczZlecenie(zlecenieDoRozliczenia.getId());
        if (res != 0) {
            throw new Exception("Blad przy zapisie w bazie danych");
        }
    }

    private void canBeADate(String czyMozeToBycData) throws Exception {
        try {
            Date d = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(czyMozeToBycData);
        } catch (Exception e) {
            System.err.println("Zly format daty");
            throw e;
        }
    }

    private boolean checkFieldsAndPrepZlecenie() throws Exception {
        try {
            if (zlecenieDoRozliczenia == null) {
                throw new ExceptionNullObject("Metoda checkAndPrep: nie ma wskazania w pamieci na obiekt zlecenieDoRozliczenia");
            }

            canBeADate(jTextField3.getText());
            BigDecimal cena1 = new BigDecimal(jTextField1.getText());
            BigDecimal cena2 = new BigDecimal(jTextField2.getText());
            if (!cena1.equals(cena2)) {
                JOptionPane.showMessageDialog(null, "Ceny nie sa rowne");
                return false;
            }
        } catch (ExceptionNullObject e) {
            JOptionPane.showMessageDialog(null, "Zly/nie aktualny wybor z listy zlecen");
            throw e;
        } catch (Exception e) {//np date zlapie jakby sie przez baze przecisnąl zly format
            JOptionPane.showMessageDialog(null, "Jedno z pole zle wypelnione");
            throw e;
        }
        return true;
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            if (checkFieldsAndPrepZlecenie()) {
                if (checkIfOperatorIsSure()) {
                    rozliczZlecenie();
                    JOptionPane.showMessageDialog(null, "Operacja zakonczona sukcesem");
                    synchonizeAllListWithDatabase();
                    fillZlecenie();
                } else {
                }
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (jList1.getSelectedValue() == null) {
            jButton2.setEnabled(false);
            return;
        }
        try {
            if (zlecenieDoRozliczenia == null) {
                throw new ExceptionNullObject("Metoda checkAndPrep: nie ma wskazania w pamieci na obiekt zlecenieDoRozliczenia");
            }
            
            String wiadomosc = "Przypomnienie platnosci. \nPobrano: " + zlecenieDoRozliczenia.getPobrano()
                    + "\nCalość do zapłaty: " + zlecenieDoRozliczenia.getDoZaplaty();
            String temat = "Przypomnienie platnosci";
            
            Mail oknoWiadomosci = new Mail(temat, wiadomosc, ramka);
            oknoWiadomosci.show();
            ramka.setVisible(false);
        } catch (Exception e) {
            System.err.println("Wyslanie emaila nieudane");
            System.err.println(e);
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jTextField1KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyTyped

    }//GEN-LAST:event_jTextField1KeyTyped

    private void jTextField2KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField2KeyTyped

    }//GEN-LAST:event_jTextField2KeyTyped

    private void jTextField3KeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField3KeyTyped

    }//GEN-LAST:event_jTextField3KeyTyped


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    // End of variables declaration//GEN-END:variables
}
